<?php
namespace Api\Domain;

use Admin\Api\MessageApi;
use Admin\Api\SecurityCodeApi;
use Admin\Model\SecurityCodeModel;
use Think\Hook;
use Uclient\Api\UserApi;

/**
 *
 * 消息查询接口
 * @author hebidu <hebiduhebi@126.com>
 * @date  15/12/5 10:28
 * @copyright by itboye.com  
 */ 
class MessageDomain extends BaseDomain
{
    protected $business_code = "message";

    //调用阿里百川的消息服务
    const MSG_TYPE_ALI_BAI_CHUAN = "bai_chuan";

    protected $allowType = array("json", "rss", "html");


    /**
     * 发送短消息
     */
    public function send_sms()
    {
        $this->checkVersion(100);

        $mobile = $this->_post("mobile","","手机号不能为空!");
        $type = $this->_post("code_type","","code_type参数不能为空!");
        $notes = $this->getTypeDesc($type);

        addLog("Message/send", $_GET, $_POST,$this->client_id."用于".$notes.",发送了验证码");

        $map = array(
            'accepter' => $mobile
        );

        $result = apiCall(SecurityCodeApi::GET_INFO, array($map,"starttime desc"));
        if($result['status'] && is_array($result['info'])){
            $info = $result['info'];
            if($info['starttime'] <  NOW_TIME && $info['starttime'] + 60*1 > NOW_TIME  ){
                //1分钟内只能向一个手机发一次信息
                $delay = 60*1  + $info['starttime'] - NOW_TIME;

                $this->apiReturnErr("请在".$delay."秒后再试!");
            }
        }

        //TODO: 考虑移走，不应该放这里检测
        $this->mobileCheck($mobile,$type);

        //生成短信验证码6位
        $code = mt_rand(100000, 999999);


        //以下测试时注释不发短信
        //1. 发送短信
        /*$result = $this->send_msg($code,$mobile,$type);

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }*/
        //以上测试时注释不发短信


        //2. 纪录到数据库
        $entity = array(
            'code' => $code,
            'accepter' => $mobile,
            'starttime' => time(),
            'endtime' => time() + 1800,
            'ip' => ip2long(get_client_ip()),
            'client_id' => $this->client_id,
            'type'=>$type,
            'status'=>0,// 未验证
        );

        $result = apiCall(SecurityCodeApi::ADD, array($entity));

        if (!$result['status']) {
            LogRecord($result['info'], __FILE__ . __LINE__);
            $this->apiReturnErr($result['info']);
        }

        //测试时返回验证码
        $this->apiReturnSuc($code);


        //$code = "短信已发送，请注意查看!";
        $this->apiReturnSuc(array('alert'=>1,'code'=>$code));


    }

    /*
     * 验证码验证
     */
    public function checkCode()
    {

        $this->checkVersion(100);

        $code=$this->_post('code','','缺少code参数');
        $mobile=$this->_post('mobile','','缺少mobile参数');
        $type = $this->_post('code_type','','缺少type参数');

        $note = $this->getTypeDesc($type);

        addLog("Message/checkCode", $_GET, $_POST,"用户".$mobile."用于".$note.",验证验证码");

        $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,$type));

        if($result['status']){
            $this->apiReturnSuc("验证通过!");
        }else{
            $this->apiReturnErr("验证失败!");
        }

    }

    /**
     * 消息查询
     */
    public function query(){
        $uid = $this->_post('uid','','用户UID缺失');
        $msg_type = $this->_post('msg_type','','消息类型缺失');
        $start_time = $this->_post('start_time',0);

        $notes = "应用" . $this->client_id . ":[用户" . $uid . "],调用消息查询接口,消息时间:".$start_time;

        addLog("Message/query", $_GET, $_POST, $notes);

        $this->checkVersion(100);

        $result = apiCall(MessageApi::QUERY_BY_UID,array($uid,$msg_type,$start_time));

        if ($result['status']) {
            $this->apiReturnSuc($result['info']);
        } else {
            $this->apiReturnErr($result['info']);
        }

    }


    //****************************私有********************************************************************

    private function mobileCheck($mobile,$type){
        $map = array(
            'mobile' => $mobile,
        );

        $result = apiCall(UserApi::FIND, array($map));

        if($type == SecurityCodeModel::TYPE_FOR_REGISTER){
            if ($result['info'] != null) {
                $this->apiReturnErr("该手机号已注册!");
            }
        }elseif($type == SecurityCodeModel::TYPE_FOR_UPDATE_PSW ){
            if ($result['info'] == null) {
                $this->apiReturnErr("该手机号未注册!");
            }
        }
    }


    private function getTypeDesc($type){

        switch($type){
            case SecurityCodeModel::TYPE_FOR_CHANGE_NEW_PHONE:
                return "更换手机";
            case SecurityCodeModel::TYPE_FOR_NEW_BIND_PHONE:
                return "绑定新手机";
            case SecurityCodeModel::TYPE_FOR_REGISTER:
                return "注册";
            case SecurityCodeModel::TYPE_FOR_UPDATE_PSW:
                return "更新密码";
            case SecurityCodeModel::TYPE_FOR_LOGIN:
                return "登陆";
            default:
                return "未知";
        }
    }


    private function send_msg($code,$mobile,$type){

        switch($type){
            case SecurityCodeModel::TYPE_FOR_CHANGE_NEW_PHONE:
                $domain_text = "更换手机";
                $type_desc = "change_phone";
                break;
            case SecurityCodeModel::TYPE_FOR_NEW_BIND_PHONE:
                $domain_text = "绑定新手机";
                $type_desc = "new_phone";
                break;
            case SecurityCodeModel::TYPE_FOR_REGISTER:
                $domain_text = "注册";
                $type_desc = "register";
                break;
            case SecurityCodeModel::TYPE_FOR_UPDATE_PSW:
                $domain_text = "更新密码";
                $type_desc = "update_password";
                break;
            case SecurityCodeModel::TYPE_FOR_LOGIN:
                $domain_text = "登陆";
                $type_desc = "login";
                break;
            default:
                $domain_text = "未知";
                $type_desc = "unknown";
                break;
        }
        $params = array(
            'domain_text'=>$domain_text,
            'domain'=>$type_desc,
            'code'=>$code,
            'mobile'=>$mobile,
        );

        Hook::listen("boye_api_message_send",$params);

        return $params;
    }


}